<template>
  <view>
    <view class="top-view">
      <uni-nav-bar
        title="护士上门"
        backgroundColor="transparent"
        :shadow="false"
        :border="false"
        :statusBar="true"
        color="white"></uni-nav-bar>
    </view>
    <view class="title-view">
      <text class="tip">您好，\n欢迎使用医院端</text>
      <image src="../../static/login_pic.png" class="img"></image>
    </view>
    <view class="card-view">
      <!-- 手机号验证码登录区域 -->
      <view class="form-item" v-if="isPhoneLogin">
        <view class="label">手机号</view>
        <input
          placeholder="请输入手机号"
          v-model="form.telNum"
          placeholder-class="placeholder-class"
          type="number"
          maxlength="11" />
        <view class="div-line" />
      </view>
      <view class="form-item" v-if="isPhoneLogin">
        <view class="label">验证码</view>
        <view class="verification-code-view">
          <input
            placeholder="请输入验证码"
            v-model="form.sendCode"
            placeholder-class="placeholder-class"
            maxlength="6"
            type="number" />
          <view class="get-code-btn" v-if="status === 'get'" @click="getCode">
            获取验证码
          </view>
          <view class="countdown" v-else>{{ statusText }}</view>
        </view>
        <view class="div-line" />
      </view>

      <!-- 用户名密码登录区域 -->
      <view class="form-item" v-if="!isPhoneLogin">
        <view class="label">用户名</view>
        <input
          placeholder="请输入用户名"
          v-model="form.username"
          placeholder-class="placeholder-class"
          type="text" />
        <view class="div-line" />
      </view>
      <view class="form-item" v-if="!isPhoneLogin">
        <view class="label">密码</view>
        <input
          placeholder="请输入密码"
          v-model="form.password"
          placeholder-class="placeholder-class"
          type="password" />
        <view class="div-line" />
      </view>

      <view class="btn-view">
        <view class="login-btn" @click="navToIndex">登录</view>
        <view class="reg-btn" @click="toggleLoginType">
          {{ isPhoneLogin ? "切换到用户名密码登录" : "切换到手机号验证码登录" }}
        </view>
      </view>
    </view>

    <view class="bottom-view">
      <radio
        color="#2EB0D9"
        @click="radioClick"
        :checked="radioSelected"></radio>
      <view class="text">登录即同意</view>
      <view class="item">《隐私政策》</view>
      <view class="text">和</view>
      <view class="item">《用户协议》</view>
    </view>
  </view>
</template>

<script>
import * as phoneCode from "../../common/api/phoneCode.js";
export default {
  data() {
    return {
      // 控制登录方式：true为手机号验证码登录，false为用户名密码登录
      isPhoneLogin: true,
      form: {
        telNum: "",
        sendCode: "",
        username: "",
        password: "",
        logType: "hospital",
      },
      radioSelected: false,
      status: "get",
      statusText: "",
      openId: "",
      templateIds: "MM43WkRzz_BCBQti-dtKD1nnV1DEsGIPJ5fhVf84pJw",
      timer: null,
    };
  },
  methods: {
    // 切换登录方式
    toggleLoginType() {
      this.isPhoneLogin = !this.isPhoneLogin;
      // 切换时清空另一种登录方式的输入内容
      if (this.isPhoneLogin) {
        this.form.username = "";
        this.form.password = "";
      } else {
        this.form.telNum = "";
        this.form.sendCode = "";
        // 清除验证码倒计时
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = null;
          this.status = "get";
        }
      }
    },
    getCode() {
      // 验证手机号
      if (!this.form.telNum) {
        uni.showToast({ title: "请输入手机号", icon: "none" });
        return;
      }
      if (this.form.telNum.length !== 11) {
        uni.showToast({ title: "请输入11位手机号", icon: "none" });
        return;
      }

      this.status = "wait";
      let seconds = 60;
      this.statusText = `重新获取${seconds}s`;
      phoneCode
        .getSMSCode(this.form.telNum)
        .then((res) => {
          this.timer = setInterval(() => {
            seconds--;
            this.statusText = `重新获取${seconds}s`;
            if (seconds <= 0) {
              clearInterval(this.timer);
              this.timer = null;
              this.status = "get";
            }
          }, 1000);
        })
        .catch((err) => {
          // 获取验证码失败时重置状态
          clearInterval(this.timer);
          this.timer = null;
          this.status = "get";
          uni.showToast({ title: "获取验证码失败", icon: "none" });
        });
    },
    checkForm() {
      const showMsg = (msg) => {
        uni.showToast({ title: msg, icon: "none" });
      };

      // 验证协议勾选
      if (!this.radioSelected) {
        showMsg("请先勾选协议");
        return false;
      }

      // 根据登录方式验证表单
      if (this.isPhoneLogin) {
        // 手机号验证码登录验证
        if (!this.form.telNum) {
          showMsg("手机号不能为空");
          return false;
        }
        if (this.form.telNum.length !== 11) {
          showMsg("请输入11位手机号");
          return false;
        }
        if (!this.form.sendCode) {
          showMsg("验证码不能为空");
          return false;
        }
        if (this.form.sendCode.length !== 6) {
          showMsg("请输入6位验证码");
          return false;
        }
      } else {
        // 用户名密码登录验证
        if (!this.form.username) {
          showMsg("用户名不能为空");
          return false;
        }
        if (!this.form.password) {
          showMsg("密码不能为空");
          return false;
        }
      }

      return true;
    },
    navToIndex() {
      if (!this.checkForm()) {
        return;
      }
      // 获取openId逻辑
      wx.login({
        success: async (res) => {
          const code = res.code;
          const phone = this.form.telNum;
          try {
            const res2 = await phoneCode.getOpenId({ code, phone });
            const openId = res2.data.data.wxOpenId;
            uni.setStorageSync("openid", openId);
          } catch (err) {
            console.error("获取openId失败：", err);
          }
        },
      });

      // 处理登录参数（移除当前登录方式不需要的字段）
      if (this.isPhoneLogin) {
        console.log("手机号验证码登录信息：");
        const param = Object.assign({}, this.form);
        console.log("param：", param);
        phoneCode
          .login(param)
          .then((result) => {
            console.log(JSON.stringify(result));
            uni.setStorageSync("user_info", JSON.stringify(result.data.data));
            uni.switchTab({
              url: "/pages/index/index",
            });
          })
          .catch((error) => {
            console.log(error);
            uni.showToast({
              title: error || "登录失败",
              icon: "error",
              duration: 2000,
            });
          });
      } else {
        console.log("用户名密码登录信息：");
        console.log("用户名：", this.form.username);
        console.log("密码：", this.form.password);
        this.form.telNum = this.form.username;
        this.form.pwd = this.form.password;
        const param = Object.assign({}, this.form);
        // 登录请求
        phoneCode
          .pwdLogin(param)
          .then((result) => {
            console.log("登录结果：", JSON.stringify(result));
            uni.setStorageSync("user_info", JSON.stringify(result.data.data));
            uni.switchTab({ url: "/pages/index/index" });
            if (!result.data.data.templateId) {
              console.error("没有templateId，发起订阅");
              this.subscribeMsg();
            }
          })
          .catch((error) => {
            console.log("登录失败：", error);
            uni.showToast({
              title: error || "登录失败",
              icon: "error",
              duration: 2000,
            });
          });
      }
    },
    subscribeMsg() {
      const templateIds = ["MM43WkRzz_BCBQti-dtKD1nnV1DEsGIPJ5fhVf84pJw"];
      uni.requestSubscribeMessage({
        tmplIds: templateIds,
        success: (res) => {
          if (res["MM43WkRzz_BCBQti-dtKD1nnV1DEsGIPJ5fhVf84pJw"] === "accept") {
            console.log("用户同意订阅");
            this.sendMsgToServer();
          } else {
            uni.showToast({ title: "订阅失败，无法接收通知", icon: "none" });
          }
        },
        fail: (err) => {
          console.error("订阅失败:", err);
          uni.showToast({ title: "订阅失败，请重试", icon: "none" });
        },
      });
    },
    async sendMsgToServer() {
      try {
        const res = await uni.request({
          url: "https://applet.youtuyiliao.com/api/hsServer/hospitalInfo/updateHospital",
          method: "POST",
          data: {
            templateId: this.templateIds,
            type: "user",
            openId: uni.getStorageSync("openid"),
          },
        });
        console.log("订阅消息发送结果：", res);
        if (res.data.code === 200) {
          uni.showToast({ title: "消息订阅成功" });
        } else {
          uni.showToast({ title: "订阅信息提交失败", icon: "none" });
        }
      } catch (error) {
        console.error("订阅请求失败:", error);
      }
    },
    noCheckToIndex() {
      uni.switchTab({ url: "/pages/index/index" });
    },
    radioClick() {
      this.radioSelected = !this.radioSelected;
    },
  },
  onUnload() {
    // 页面卸载时清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
      this.status = "get";
    }
  },
};
</script>
<style>
page {
  background: white;
}
</style>
<style lang="scss" scoped>
/* 样式保持不变 */
.top-view {
  width: 100%;
  height: 680rpx;
  background: linear-gradient(to left, #2db8d7, #86dffc);
}

.title-view {
  display: flex;
  margin-left: 50rpx;
  margin-right: 50rpx;
  margin-top: -500rpx;
  align-items: center;

  .tip {
    font-size: 44rpx;
    color: white;
    line-height: 50rpx;
    flex: 1;
  }

  .img {
    width: 270rpx;
    height: 270rpx;
  }
}

.card-view {
  background: white;
  border-radius: 32rpx 32rpx 0rpx 0rpx;
  padding: 0 60rpx;

  .form-item {
    display: flex;
    flex-direction: column;
    padding-top: 50rpx;

    .label {
      color: #232323;
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 30rpx;
    }

    input {
      font-size: 30rpx;
      flex: 1;
    }

    .placeholder-class {
      font-size: 30rpx;
      color: rgba(35, 35, 35, 0.26);
    }

    .verification-code-view {
      display: flex;
      align-items: center;
    }

    .get-code-btn {
      color: #2eb0d9;
      font-size: 30rpx;
    }

    .countdown {
      color: rgba(35, 35, 35, 0.26);
      font-size: 30rpx;
    }

    .div-line {
      height: 2rpx;
      background: #f2f2f2;
      margin-top: 30rpx;
    }
  }

  .btn-view {
    width: 100%;
    margin-top: 60rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .login-btn {
      width: 100%;
      background: #2eb0d9;
      height: 84rpx;
      border-radius: 42rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 32rpx;
    }

    .reg-btn {
      margin-top: 50rpx;
      color: #2eb0d9;
      font-size: 28rpx;
    }
  }
}

.bottom-view {
  width: 100%;
  margin-top: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;

  radio {
    transform: scale(0.7);
  }

  .text {
    color: rgba(35, 35, 35, 0.6);
    font-size: 24rpx;
  }

  .item {
    color: #2eb0d9;
    font-size: 24rpx;
  }
}
</style>
